package dtd.PHS.VND_ExchangeRate.data;

import java.util.ArrayList;

import org.apache.http.protocol.ExecutionContext;

import dtd.PHS.VND_ExchangeRate.data.RateItem.MyCurrency;
import dtd.PHS.VND_ExchangeRate.utils.MyHandler;


public class DataProvider {

	private static DataProvider instance;

	private DataProvider() {}

	public static DataProvider getInstance() {
		if ( instance == null ) {
			instance = new DataProvider();
		}
		return instance;
	}

	public void requestListRates(final IDelegateDataGetter delegate) {
		Thread t = new Thread( new Runnable() {
			@Override
			public void run() {
				try {
					final ListRates rates = VNExDatabase.getListRates();
					MyHandler.getInstance().post(new Runnable() {					
						@Override
						public void run() {
							if ( delegate != null )
								delegate.onGetDataCompleted(rates);						
						}
					});
				} catch (Exception e) {
					final Exception ef = e;
					MyHandler.getInstance().post(new Runnable() {
						@Override
						public void run() {
							if (delegate != null) {
								delegate.onGetDataError(ef);
							}
						}
						
					});
				}
			}
		});
		t.start();
	}

	public RateItem getRate(String currencyName) {
		ListRates rates = VNExDatabase.getListRates();
		return rates.getRate(currencyName);
	}

	public ArrayList<String> getAllCurrenciesExceptVND() {
		ArrayList<String> currencies = new ArrayList<String>();
		for(MyCurrency curr : MyCurrency.values()) {
			String name = curr.toString();
			if ( !name.equals("VND")) {
				currencies.add( name );
			}
		}

		return currencies;

	}

	public MyDate getDate() {
		return VNExDatabase.getDate();
	}

	public SJCItem getGoldPrice() {
		return VNExDatabase.getGoldRate();		
	}

	public void requestGoldPrice(final IDelegateDataGetter delegate) {
		new Thread(new Runnable() {
			public void run() {
				final SJCItem price = getGoldPrice();
				MyHandler.getInstance().post(new Runnable() {
					public void run() {
						delegate.onGetDataCompleted(price);
					}
				});
			}
		}).start();
	}

}
